<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="onConfirm"
    title="新增同行"
    :mask-closable="false"
    class="modal-dialog-wrapper"
    unmount-on-close
    width="80vw"
  >
    <div class="page-container">
      <div class="store-info">
        <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
          <page-form-row>
            <page-form-item field="industryName" label="同行名称" required>
              <i-input placeholder="请输入" v-model="form.industryName" :max-length="30" />
            </page-form-item>
            <page-form-item field="cityCode" label="省/市" required>
              <city-cascader v-model="form.cityCode" @change="changeCityFn" />
            </page-form-item>
            <page-form-item field="address" label="地址" required>
              <i-input placeholder="请选择" v-model="form.address" readonly @click="siteCoordinatesClickFn" />
              <icon-location :size="25" class="icon-location" @click="siteCoordinatesClickFn" />
            </page-form-item>
          </page-form-row>
        </page-form>
      </div>
    </div>
    <!-- 坐标选择 -->
    <lnglat-picker-modal ref="lnglatPickerModalRef" @change="pointChangeFn" />
  </a-modal>
</template>

<script setup lang="ts">
  import { usePageDict } from '@/hooks/useDict'
  import { ref } from 'vue'
  import { isMobile } from '@/utils/validate'
  import { updatePeer } from '@/api/market/peer'

  const emit = defineEmits(['addNameOk'])

  const tmpChangeCityOption = ref<any>({})

  const formRef = ref()
  const form = ref<any>({
    settlementDay: 1,
    backInfoList: [],
  })
  const lnglatPickerModalRef = ref()
  const validateFn = (value: string, cb: (msg?: string) => void) => {
    if (!value || value == '') {
      cb()
    } else {
      if (!isMobile(value)) {
        cb('手机号格式不正确')
      }
    }
  }

  const rules = ref({
    industryName: { required: true, message: '请输入同行名称', trigger: 'change' },
    cityCode: { required: true, message: '请选择省/市', trigger: 'change' },
    address: { required: true, message: '请选择地址', trigger: 'change' },
    contactName: { required: false, message: '请输入姓名' },
    contactPhone: { required: false, validator: validateFn },
    invoicePhone: { required: false, maxLength: 20 },
  })

  const changeCityFn = (value: string, option: any) => {
    if (tmpChangeCityOption.value && tmpChangeCityOption.value.cityCode == option.cityCode) {
      return
    }
    form.value.provinceCode = option.provinceCode
    form.value.cityCode = option.cityCode
    form.value.address = ''
    tmpChangeCityOption.value = option
  }

  const siteCoordinatesClickFn = () => {
    lnglatPickerModalRef.value.open().then((map: any) => {
      lnglatPickerModalRef.value.setCity(map, form.value.cityCode)
    })
  }

  const pointChangeFn = (lnglat: number[], option: any) => {
    form.value.address = option.formattedAddress
    form.value.longitude = lnglat[0]
    form.value.latitude = lnglat[1]
    if (option) {
      const adcode = option.addressComponent.adcode
      form.value.address = option.formattedAddress
      form.value.provinceCode = String(parseInt((adcode / 10000) as unknown as string) * 10000)
      form.value.cityCode = String(parseInt((adcode / 100) as unknown as string) * 100)
      form.value.districtCode = adcode
      // fixme: 坐标选择无法返回省份 code，此时无法更新 form.provinceCode
      // 如果直接调接口目前也没问题 provinceCode 非必填，且后端会补 provinceCode 数据

      formRef.value.validateField(['cityCode', 'address'])
    }
  }

  const showModal = ref(false)

  const show = () => {
    showModal.value = true
  }
  const onClose = () => {
    showModal.value = false
    form.value = {
      settlementDay: 1,
      backInfoList: [],
    }
  }
  const validateFormFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          console.log(error)
          reject()
        } else {
          resolve()
        }
      })
    })
  }

  const onConfirm = () => {
    return new Promise((resolve, reject) => {
      validateFormFn()
        .then(async () => {
          updatePeer(form.value)
            .then((res) => {
              // 成功提示
              emit('addNameOk', res.result)
              onClose()
              resolve()
            })
            .catch(() => {
              reject()
            })
            .finally(() => {
              tmpChangeCityOption.value = {}
            })
        })
        .catch(() => {
          reject()
        })
    })
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .page-container {
    max-height: 70vh;
  }
  :deep(.custom-divider) {
    margin-top: 0;
  }
  .upload-wrapper,
  .settlement-method {
    padding: 20px 0 0;
  }

  .upload-wrapper {
    margin-bottom: 20px;
  }

  .alert-txt {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1d2129;
    line-height: 22px;
  }

  .settlement-method {
    width: 438px;
    padding: 16px 16px;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    border: 1px solid #e5e8ef;
    margin-top: 16px;
    box-sizing: border-box;

    .method-radio {
      display: flex;

      .arco-radio {
        width: max-content;
      }
    }

    .day-box {
      width: 372px;
      display: flex;
      background: rgba(247, 248, 250, 0.5);
      border-radius: 0px 0px 0px 0px;
      opacity: 1;
      box-sizing: border-box;
      padding: 16px;
      align-items: center;

      .day-txt {
        margin-left: 16px;
        white-space: nowrap;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #1d2129;
        line-height: 22px;
      }
    }
  }
  .mr-20px {
    margin-right: 20px;
  }

  .icon-location {
    display: inline-block;
    width: 25px;
    height: 32px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
